package com.the9.C9Alarm;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmSet {
	static Intent intent;
	static PendingIntent pendingIntent;
	
	public static void setAlarm(Context c) {
		// 设定闹钟
		AlarmBean ab = AlarmProvider.geInstance(c).getNextAlarm();
		AlarmManager am = (AlarmManager) c
				.getSystemService(Context.ALARM_SERVICE);
		if (ab != null) {

			intent = new Intent(c, AlarmReceiver.class);
			intent.setAction(Symbol.ACTION_RECEIVE_ALARM);
			intent.putExtra("alarm_index", ab.getIndex());
			pendingIntent = PendingIntent.getBroadcast(c, 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);

			
			am.set(AlarmManager.RTC_WAKEUP, ab.getTime(), pendingIntent);
		}else{//取消闹钟
			intent = new Intent(c, AlarmReceiver.class);
			intent.setAction(Symbol.ACTION_RECEIVE_ALARM);
			pendingIntent = PendingIntent.getBroadcast(c, 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			am.cancel(pendingIntent);
		}
		
		
		Intent intentNotification ;
		
		PendingIntent pINotificiation ;
		NotificationManager nfManger = (NotificationManager) c
				.getSystemService(Activity.NOTIFICATION_SERVICE);	
		Notification mNotification = new Notification();
		
		// 设定消息
		if (ab != null) {
			intentNotification = new Intent(c, AlarmReceiver.class);
			intentNotification.setAction(Symbol.ACTION_START_MAIN);
			pINotificiation = PendingIntent.getBroadcast(c, 0,
					intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
			
			Long nextTime = ab.getTime();
			Calendar cl = Calendar.getInstance();
	        cl.setTimeInMillis(nextTime);
	        String showText = Utils.getFormatedDayString(cl);
			
			mNotification.icon = R.drawable.ic_clock_add_alarm;
			mNotification.tickerText = "闹钟将在"
					+ Utils.getFormatTime((int) ((nextTime - System
							.currentTimeMillis()) / 1000)) + "后再次启动";
			mNotification.flags |= mNotification.FLAG_NO_CLEAR; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
			mNotification.setLatestEventInfo(c, "下次闹钟时间", showText, pINotificiation);
			
			nfManger.notify(Symbol.NOTIFICATION_MESSAGE, mNotification);
		} else {

			intentNotification = new Intent(c, AlarmReceiver.class);
			intentNotification.setAction(Symbol.ACTION_DONOTHING);
			pINotificiation = PendingIntent.getBroadcast(c, 0,
					intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
			
			
			mNotification.icon = R.drawable.ic_clock_add_alarm;
			mNotification.tickerText = "目前没有启用闹钟";
			mNotification.flags |= mNotification.FLAG_AUTO_CANCEL; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
			mNotification.setLatestEventInfo(c, "没有设定闹钟", "点击关闭提示", pINotificiation);
			nfManger.notify(Symbol.NOTIFICATION_MESSAGE, mNotification);
			
		}

	}

}
